<template>
  <div class="cart">

    <ul>
      <!-- <li v-for="(item,index) in $store.state.cartList" :key="item.id"></li> -->
      <van-swipe-cell v-for="(item, index) in cartList" :key="item.id">
        <li>
          <van-checkbox v-model="item.flag" @change="checkone"></van-checkbox>
          <img :src="item.img" alt="">
          <section>
            <h4>{{ item.name }}</h4>
            <div class="ft_right">
              <span>￥{{ item.price }}</span>
              <van-stepper v-model="item.buyNum" />
            </div>
          </section>
        </li>
        <template #right>
          <van-button square text="删除" type="danger" class="delete-button" @click="del(index)" />
        </template>
      </van-swipe-cell>
    </ul>
    <van-submit-bar :price="allPrice" button-text="提交订单">
      <van-checkbox v-model="checked" @click="checkAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
  data() {
    return {
      checked: false, // 全选的变量
    }
  },
  computed: {
    ...mapState(['cartList']), // vuex的辅助函数
    allPrice() { // 选中的总价
      let price = 0;
      this.cartList.forEach(item => {
        if (item.flag) {
          price += item.price * item.buyNum
        }
      })
      return price * 100;
    }
  },
  methods: {
    ...mapMutations(['del']),
    checkAll() { // 全选的事件
      this.cartList.forEach(item => {
        item.flag = this.checked;
      })
    },
    checkone() { // 反选的事件
      this.checked = this.cartList.every(item => item.flag);
    }
  }
}
</script>
<style lang="scss" scoped>
.cart {
  background-color: #fff;
}

li {
  display: flex;
  padding: 10px;
  box-sizing: border-box;
  align-items: center;

  img {
    width: 60px;
    margin: 0 10px;
  }

  section {
    font-size: 15px;
    flex: 1;

    .ft_right {
      display: flex;
      justify-content: space-between;

      span {
        color: red;
      }
    }
  }
}

.delete-button {
  height: 100%;
}

.van-submit-bar {
  bottom: 50px;
}
</style>